# -*- coding: utf-8 -*-
"""
@Time ： 2024/9/24 10:14
@Auth ： 九问
@File ：serializers.py
@IDE ：PyCharm
@Email : 2750826557@qq.com
"""
import json

from rest_framework import serializers

from users.models import UserDetail
from .models import Message


class UserDetailSerializer(serializers.ModelSerializer):
    first_name = serializers.CharField(source='user.first_name', read_only=True)

    class Meta:
        model = UserDetail
        fields = ['avatar', 'first_name']


class MessageSerializer(serializers.ModelSerializer):
    user_details = UserDetailSerializer(source='sender.userdetail', read_only=True)

    class Meta:
        model = Message
        fields = ['sender', 'text', 'timestamp', 'user_details']

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        user_details = rep.get('user_details', {})

        # 处理 message 字段
        message = rep['text'].replace("'", '"')  # 替换单引号为双引号
        try:
            json_message = json.loads(message)  # 尝试解析为 JSON
        except json.JSONDecodeError:
            json_message = message  # 如果解析失败，保留原始文本
        return {
            'avatar': user_details.get('avatar'),
            'username': user_details.get('first_name'),
            'message': json_message
        }
